package com.bocom.hairy.crab.consumer.interceptor;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

/**
 * 全局Header拦截器：统一添加请求头
 */
public class HeaderInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        HttpHeaders headers = request.getHeaders();

        // 添加全局Header（根据业务需求调整）
        headers.add("User-Agent", "crab-consumer-RestTemplate");
        headers.add("Accept", "application/json");
        headers.add("X-App-Id", "crab-consumer"); // 应用标识
        headers.add("X-Request-Id", generateRequestId()); // 唯一请求ID，用于追踪

        // 执行请求
        return execution.execute(request, body);
    }

    /**
     * 生成唯一请求ID（简单实现，生产环境可使用更完善的ID生成策略）
     */
    private String generateRequestId() {
        return System.currentTimeMillis() + "-" + Thread.currentThread().getId();
    }
}

